/*
 * Wantmore - Service Delivery Platform.
 *
 * $Id: AlbumEditFormController.java 60 2010-10-13 07:26:24Z alexey.batyuta@gmail.com $
 *
 * Copyright 2010 by Sunbay Software Crimea Ltd.
 * All rights reserved
 */
package ua.crimea.bat.ss.forms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import ua.crimea.bat.ss.model.beans.Album;
import ua.crimea.bat.ss.model.validators.AlbumValidator;
import ua.crimea.bat.ss.services.PhotoAlbumsService;

/**
 * User: bat
 * Date: Mar 26, 2010
 * Time: 9:05:29 AM
 */
@Controller("albumEditFormController")
@RequestMapping("/albums/{albumId}/edit")
@SessionAttributes(types = Album.class)
public class AlbumEditFormController {
protected PhotoAlbumsService photoAlbumsService;

    public AlbumEditFormController() {
    }

    public void setPhotoAlbumsService(PhotoAlbumsService photoAlbumsService) {
        this.photoAlbumsService = photoAlbumsService;
    }

    public PhotoAlbumsService getPhotoAlbumsService() {
        return photoAlbumsService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    @Autowired
    public AlbumEditFormController(PhotoAlbumsService photoAlbumsService) {
        this.photoAlbumsService = photoAlbumsService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@PathVariable("albumId") int albumId, Model model) {
        Album album = photoAlbumsService.loadAlbum(albumId);
        model.addAttribute(album);
        return "albums/form";
    }

    @RequestMapping(method = RequestMethod.PUT)
    public String processSubmit(@ModelAttribute Album album, BindingResult result, SessionStatus status) {
        new AlbumValidator().validate(album, result);
        if (result.hasErrors()) {
            return "albums/form";
        } else {
            photoAlbumsService.storeAlbum(album);
            status.setComplete();
            return "redirect:/albums/" + album.getId();
        }
    }

}
